/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlador;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;

/**
 *
 * @author Windows7
 */
public class LoginControl extends HttpServlet {
  Connection conn = null;
  String imagespath = null;

  public void init (ServletConfig config) throws ServletException {

    super.init(config);
    imagespath = "";

    String url=new String("jdbc:mysql://localhost:3306/hms");
    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch(ClassNotFoundException ex) {
      System.out.println("Error al cargar el driver");
      System.out.println(ex.getMessage());
    }
    try {
      conn=DriverManager.getConnection(url,"root","mysql");
    } catch (SQLException sqlEx) {
      System.out.println("Se ha producido un error al establecer la conexion con: "+url);
      System.out.println(sqlEx.getMessage());
    }
  }

  public void destroy () {
    super.destroy();
    System.out.println("Cerrando conexion...");
    try {
      conn.close();
    } catch(SQLException ex){
      System.out.println("No se pudo cerrar la conexion");
      System.out.println(ex.getMessage());
    }
  }

  public void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Statement stmt = null;
    ResultSet rs = null;
    String DB_password = null;
    
    String username = null;
    String password = null;
    username = req.getParameter("username");
    password = req.getParameter("password");

    if(username==null) {
      System.out.println("Se ha producido un error en la lectura de la solicitud");
      return;
    }
    if(password==null) {
      System.out.println("Se ha producido un error en la lectura de la solicitud");
      return;
    }
    try {
      stmt=conn.createStatement();
      rs = stmt.executeQuery("SELECT * FROM `hms`.`usuario` WHERE UsuLog = '" + username+"'");
      
	  
      if(rs.next()==false){
        Error_Username(req, resp);
        return;
      }else{
	  DB_password = rs.getString("UsuPas");          
	  if(password.equals(DB_password)) {
          HttpSession session = req.getSession(true);
          String ocupacion = rs.getString("UsuOcu");
          
          String Id_Cliente = rs.getString("Id_Usuario");          
          String Nombre_Cliente = rs.getString("UsuNom") + " " + rs.getString("UsuApe");
          String Username = rs.getString("UsuLog");
          session.putValue("Id",Id_Cliente);
          session.putValue("Nombre",Nombre_Cliente);
          session.putValue("Username", Username);
          DevolverHTML(req, resp,ocupacion);
          return;
	  }else {
          Error_Password(req, resp);
          return;
	  }
      }
    } catch (SQLException sql) {
      System.out.println("Se produjo un error al crear el Statement");
      System.out.println(sql.getMessage());
      return;
    } finally {      
      if(stmt!=null) {
        try {
          stmt.close();
        } catch(SQLException e) {
          System.out.println("Error al cerrar el Statement");
          System.out.println(e.getMessage());
          return;
        }
      }
    } 
  } 

  public void DevolverHTML(HttpServletRequest req, HttpServletResponse resp, String ocupacion) {

    HttpSession session = req.getSession(false);
    resp.setContentType("text/html");

    PrintWriter out=null;
    try {
      out=resp.getWriter();
    } catch (IOException io) {
      System.out.println("Se ha producido una excepcion");
    }
    out.println("<html>");
    out.println("<head>");
    out.println("<title></title>");
    out.println("</head>");
    out.println("<frameset cols=\"100,*\">");
    if(session != null){
       /* 
      String Usuario = (String) session.getValue("Username");
      if(Usuario.equals("administrador") == true){
        
          out.println("<H2 align=\"center\">" + session.getValue("Nombre"));       
        out.println("<A HREF=\"Registro_Disco\"><IMG BORDER=0 SRC=\"" + imagespath + "Add_Disco.jpg\"></A>");
        out.println("<A HREF=\"Ver_Clientes\"><IMG BORDER=0 SRC=\"" + imagespath + "Clientes.jpg\"></A>");
        out.println("<A HREF=\"Logout\"><IMG BORDER=0 SRC=\"" + imagespath + "Salir.jpg\"></A></H2>");
        out.println("<HR>");
         
      }else{
                  
      } 
        * 
        */     
      
    }
    out.println("<frame name=\"menu\" target=\"main\" src=\"WUIMenu"+ocupacion+".jsp\" scrolling=\"auto\" noresize>");
    out.println("<frame name=\"contenido\" src=\"WUI"+ocupacion+".jsp\" scrolling=\"auto\" noresize>");
        //out.println("<p><a href='WUI"+ocupacion+".jsp'>Entrar</a>"); 
    out.println("<noframes>");
    out.println("<body>");
    out.println("<p></p>");
    out.println("</body>");
    out.println("</noframes>");
    out.println("</frameset>");
    out.println("</html>");
    out.flush();
    out.close();  
  }

  public void Error_Username(HttpServletRequest req, HttpServletResponse resp) {

    resp.setContentType("text/html");
    PrintWriter out=null;
    try {
      out=resp.getWriter();
    } catch (IOException io) {
      System.out.println("Se ha producido una excepcion");
    }
    out.println("<html>");
    out.println("<head>");
    out.println("<title></title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<BR>");
    out.println("<H2 align=\"center\">El <B>Nombre de Usuario</B> no existe</H2>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
    out.close();
  }

  public void Error_Password(HttpServletRequest req, HttpServletResponse resp) {

    resp.setContentType("text/html");
    PrintWriter out=null;
    try {
      out=resp.getWriter();
    } catch (IOException io) {
      System.out.println("Se ha producido una excepcion");
    }
    out.println("<html>");
    out.println("<head>");
    out.println("<title></title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<BR>");
    out.println("<H2 align=\"center\">La <B>Contraseña</B> introducida no es correcta</H2>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
    out.close();
  }
}
